package com.ext.demoredis.common;


import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.stereotype.Component;

import java.util.concurrent.TimeUnit;

@Component
public class DistributedLock {

    @Autowired
    private StringRedisTemplate template;

    /**
     * 获得锁
     */
    public boolean getLock(String lockId,String value, long millisecond) {
        Boolean success = template.opsForValue().setIfAbsent(lockId, value,
                millisecond, TimeUnit.MILLISECONDS);
        return success != null && success;
    }
    /**
     * 释放锁
     */
    public void releaseLock(String lockId) {
        template.delete(lockId);
    }
}
